import { Injectable } from "@angular/core";
import { castArray } from "lodash-es";
import * as _moment from 'moment';
import { PreviewFormDesignService } from "../preview-form-design.service";

declare const JSONPath: any;
@Injectable({
  providedIn: 'root'
})
export class ErmsFormDesignService {
  constructor(
    private _previewFormDesignService: PreviewFormDesignService,
    //private _FormDesignService: FormDesignService,
  ) {}
  isOldTemplate(showTemplate: string): boolean {
    return showTemplate.startsWith('<?xml');
  }

  getInitInfo(showTemplate, jsonMetadata) {
    console.log(jsonMetadata);
    
    const showTemplateXml = JSON.parse(showTemplate)
    const result = this._previewFormDesignService.getFlatList({list: showTemplateXml.list})
    const final = {}
    for (const item of result) {
      const path = item.key.replace('.content', '')
      const result = JSONPath.JSONPath({ path: path, json: jsonMetadata, resultType: 'all' })
      if (result[0]?.value?.content) {
        final[item.key] = result[0]?.value?.content
      }
    }
    const find = result.find(item => item.type == 'process')
    if (find) {
      const node = this.getProcessNode((jsonMetadata as any)?.record)
      if (node) {
        final[find.key] = node
      }
    }
    const width = showTemplateXml.config.previewWidth;

    return {
      initValue: final,
      showTemplateXml,
      width
    }
  }

  saveData(jsonData, value, template) {
    const flatList = this._previewFormDesignService.getFlatList({list: template.list})
    const flatMap = flatList.reduce((prev, cur) => {
      prev[cur.model] = cur
      return prev
    }, {})
    // debugger
    for (let key in value) {
      let path = key.replace('.content', '')
      let result = JSONPath.JSONPath({ path: path, json: jsonData, resultType: 'all' })
      if (result[0] && value[key]) {
        if (typeof value[key] == 'string') {
          result[0].value.content = value[key]
        } else {
          const info = flatMap[key]
          if (info.type == 'date') {
            result[0].value.content = _moment(value[key]).format(info.options.format.replace('yyyy','YYYY').replace('dd','DD'))
          } else {
            result[0].value.content = JSON.stringify(value[key]);
          }
        }
        //const content = typeof value[key] == 'string' ? value[key] : _moment(value[key]).format('YYYY-MM-DD')
      }
    }
  }

  getProcessNode(json) {
    const formatShowJson = (jsonData) => {
      if (jsonData.node) {
        return castArray(jsonData.node);
      }
      if (jsonData.block) {
        const blocks = castArray(jsonData.block)
        for (let i = 0; i < blocks.length; i++) {
          const result = formatShowJson(blocks[i])
          if (result) {
            return result;
          }
        }
      }
      return null;
    }
    return formatShowJson(json)
  }
}